<?php

include 'lib.php';


ini_set('display_errors', 1);
$posts = Database::find("posts", array("images_scraped" => '0'), null, "RAND()", 50);

$download = $_GET['download'];
var_dump($posts);

foreach ($posts as $post)
{
    scrapeImages($post, $download);
}

function scrapeImages($post, $download)
{
    Database::save("posts", array("id" => $post['id'], 'images_scraped' => '1'));
    
    $html_text = file_get_contents($post['link']);

    $html = new DomDocument();
    $html->preserveWhiteSpace = false;
    
    $html->loadXML($html_text);
    $html->loadHTML($html_text);
    $xpath = new DomXPath($html);    
    
    $images = $html->getElementsByTagName('img');
    
    foreach ($images as $image)
    {
        $exists = Database::find("photos", array("original_src" => $image->getAttribute("src")));

        if (!$exists)
        {
            $src = $image->getAttribute("src");

                $parts = explode('.', $src);
                $extension = trim(strtolower($parts[count($parts)-1]));
                
                echo $extension;
                if ($extension == "jpeg") $extension = "jpg";
                            
                $photo_id = Database::save("photos", array(
                    'object_type' => 'post',
                    'object_key' => $post['id'],
                    'original_src' => $src,
                    'date' => date('Y-m-d H:i:s'),
                    'type' => 'original',
                    'format' => $extension
                ));
                
                var_dump($photo_id);
                
                if ($download)
                {
                    $manager = new ImageManager(urlsafe($src));
    
                    Database::save("photos", array(
                        'id' => $photo_id,
                        'width' => imagesx($manager->image),
                        'height' => imagesy($manager->image),
                    ));

                    if (imagesx($manager->image) < 100 || imagesy($manager->image) < 100) continue;

                    $manager->save("img/posts/$photo_id.jpg");
                    
                    $manager->resize(100,100);
                    $manager->save("img/post_thumbs/$photo_id.jpg");
                }

            
        }
    }
}

?>